package com.cx.web.config;

import com.cx.meta.annotation.EnumData;
import com.google.common.collect.Lists;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;

/**
 * @author flysand
 * @package com.cx.web.config
 * @date 2021-11-21 03:07
 * @des SpringCache: 用于缓存spring容器启动后要（一次性）加载到map缓存中的数据
 */
public class SpringCache {

    private final String classPath = "com.cx.meta.enums";


    @PostConstruct
    public void cacheMapData() {
        // 一次性缓存所有需要给前端的枚举类

        List<Class> classes = Lists.newArrayList();
        String packageDir = classPath.replace(".","/");
        Enumeration<URL> dir;
        try {
             dir = Thread.currentThread().getContextClassLoader().getResources(packageDir);
            while (dir.hasMoreElements()) {
                URL url = dir.nextElement();
                String protocol = url.getProtocol();
                if (protocol.equals("file")){
                    File classDir = new File(url.getPath());
                    File[] files = classDir.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File pathname) {
                            return pathname.getName().endsWith(".class");
                        }
                    });
                    for (File file : files) {
                        String className = file.getName().substring(0,file.getName().length()-6);
                        Class clazz = Thread.currentThread().getContextClassLoader().loadClass(classPath + "."+className);
                        // 是否有EnumData注解
                        if (clazz.getDeclaredAnnotation(EnumData.class)!=null){
                            classes.add(clazz);
                        }

                    }

                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        // 遍历所有classes 把value 写到map
        for (Class aClass : classes) {
        }
    }

    public static void main(String[] args) {
        SpringCache cache = new SpringCache();
        cache.cacheMapData();
    }
}
